package com.wangsh.splider.task.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.csvreader.CsvReader;
import com.wangsh.splider.common.pojo.ApiResponse;
import com.wangsh.splider.common.pojo.ApiResponseEnum;
import com.wangsh.splider.common.pojo.JSONEnum;
import com.wangsh.splider.common.service.BaseServiceImpl;
import com.wangsh.splider.common.util.ConstatFinalUtil;
import com.wangsh.splider.task.pojo.ATaskUsers;
import com.wangsh.splider.task.pojo.ATaskUsersEnum;
import com.wangsh.splider.task.service.ITaskOperService;
import com.wangsh.splider.task.service.ITaskDbService;

/**
 * Task模块的Oper接口
 * @author TeaBig
 */
@Service("taskOperService")
public class TaskOperServiceImpl extends BaseServiceImpl implements ITaskOperService
{
	@Resource
	private ITaskDbService taskDbService;
	
	@Override
	public ApiResponse<Object> operUsersBatchService(Map<String, Object> paramsMap,String charset)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		apiResponse.setDataOne(dataMap);
		/* 获取配置文件 */
		File souFile = (File) paramsMap.get("souFile");
		String taskId = (String) paramsMap.get("taskId");
		
		String fileName = souFile.getName() ; 
		if(!fileName.endsWith(".csv"))
		{
			ConstatFinalUtil.SYS_LOGGER.info("当前的文件不是csv;无法导入;路径:{}",souFile.getAbsolutePath());
		}
		if(charset == null || "".equalsIgnoreCase(charset))
		{
			charset = ConstatFinalUtil.CHARSET ; 
		}
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		try
		{
			List<ATaskUsers> insertList = new ArrayList<ATaskUsers>();
			List<ATaskUsers> updateList = new ArrayList<ATaskUsers>();
			int totalCount = 0 ; 
			int succedCount = 0 ;
			int failedCount = 0 ; 
			// 创建CSV读对象
			CsvReader csvReader = new CsvReader(new FileInputStream(souFile), Charset.forName("GBK"));
			// 跳过表头
			csvReader.readHeaders();
			while (csvReader.readRecord())
			{
				totalCount ++ ; 
				String line = "" ; 
				try
				{
					line = csvReader.getRawRecord() ; 
					/* true:表示更新,false:表示添加 */
					boolean updateFlag = true ; 
					
					/* 读取数据 */
					String email = csvReader.get("email");
					String phone = csvReader.get("phone");
					/* 按照手机号和邮箱查询 */
					condMap.clear();
					condMap.put("email", email);
					condMap.put("taskId", taskId);
					ApiResponse<ATaskUsers> usersApiResponse = this.taskDbService.findOneUsersService(condMap);
					ATaskUsers taskUsers = usersApiResponse.getDataOneJava() ;
					if(taskUsers == null)
					{
						condMap.clear();
						condMap.put("email", email);
						condMap.put("taskId", taskId);
						usersApiResponse = this.taskDbService.findOneUsersService(condMap);
						taskUsers = usersApiResponse.getDataOneJava() ;
					}
					
					if(taskUsers == null)
					{
						taskUsers = new ATaskUsers();
						
						taskUsers.setCreateTime(new Date());
						updateFlag = false ;
					}
					
					taskUsers.setTaskId(Integer.valueOf(taskId));
					taskUsers.setEmail(email);
					taskUsers.setPhone(phone);
					taskUsers.setStatus(ATaskUsersEnum.STATUS_NOTSTARTED.getStatus());
					taskUsers.setUpdateTime(new Date());
					taskUsers.setPubTime(new Date());
					
					/* 增加到容器中 */
					if(updateFlag)
					{
						updateList.add(taskUsers);
					}else
					{
						insertList.add(taskUsers);
					}
					
					ApiResponse<Object> apiResponseDb = new ApiResponse<Object>();
					if(insertList.size() > 0 && insertList.size() % ConstatFinalUtil.BATCH_SIZE == 0)
					{
						apiResponseDb = this.taskDbService.saveBatchUsersService(insertList);
						/* 存储的数据 */
						Map<String, Object> dataMapJava = apiResponseDb.getDataMapJava() ; 
						if(apiResponseDb.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
						{
							int succedCountTemp = (int) dataMapJava.get(JSONEnum.EFFECT.getName());
							succedCount = succedCount + succedCountTemp ; 
							failedCount = insertList.size() - succedCountTemp ; 
						}
						
						insertList.clear();
					}
					if(updateList.size() > 0 && updateList.size() % ConstatFinalUtil.BATCH_SIZE == 0)
					{
						apiResponseDb = this.taskDbService.saveBatchUsersService(updateList);
						/* 存储的数据 */
						Map<String, Object> dataMapJava = apiResponseDb.getDataMapJava() ; 
						if(apiResponseDb.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
						{
							int succedCountTemp = (int) dataMapJava.get(JSONEnum.EFFECT.getName());
							succedCount = updateList.size() ; 
							failedCount = 0 ; 
						}
						insertList.clear();
					}
				} catch (Exception e)
				{
					ConstatFinalUtil.SYS_LOGGER.error("操作数据失败了,数据:{}",souFile,e);
				}
			}
			
			/* 循环完,清空一下数据 */
			ApiResponse<Object> apiResponseDb = new ApiResponse<Object>();
			if(insertList.size() > 0)
			{
				apiResponseDb = this.taskDbService.saveBatchUsersService(insertList);
				/* 存储的数据 */
				Map<String, Object> dataMapJava = apiResponseDb.getDataOne(); 
				if(apiResponseDb.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
				{
					int succedCountTemp = (int) dataMapJava.get(JSONEnum.EFFECT.getName());
					succedCount = succedCount + succedCountTemp ; 
					failedCount = insertList.size() - succedCountTemp ; 
				}
				
				insertList.clear();
			}
			if(updateList.size() > 0)
			{
				apiResponseDb = this.taskDbService.updateBatchUsersService(updateList);
				/* 存储的数据 */
				Map<String, Object> dataMapJava = apiResponseDb.getDataOne() ; 
				if(apiResponseDb.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
				{
					int succedCountTemp = (int) dataMapJava.get(JSONEnum.EFFECT.getName());
					succedCount = updateList.size() ; 
					failedCount = 0 ; 
				}
				insertList.clear();
			}
			/* 运行结果 */
			dataMap.put("totalCount", totalCount);
			dataMap.put("succedCount", succedCount);
			dataMap.put("failedCount", failedCount);
			
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("写文件(csv)失败了,路径:{},编码:{}",souFile,charset,e);
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}
}
